﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace TfsExtensions.Build.Activities
{
    public sealed class InvokeMRefBuilder : CodeActivity
    {
        [RequiredArgument]
        public InArgument<string> ReflectionOrgFilename { get; set; }

        [RequiredArgument]
        public InArgument<string> SandcastleProductionToolsFolder { get; set; }

        [RequiredArgument]
        public InArgument<string> WorkingFolderName { get; set; }

        [RequiredArgument]
        public InArgument<Collection<string>> Assemblies { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            var exeFileName = string.Format(@"{0}\MrefBuilder.exe", this.SandcastleProductionToolsFolder.Get(context));

            var assemblyList = this.Assemblies.Get(context);
            if (assemblyList != null)
            {
                StringBuilder assemblyNames = new StringBuilder();
                foreach (var assembly in assemblyList)
                {
                    assemblyNames.Append("\"" + assembly + "\"");
                    assemblyNames.Append(" ");
                }

                var assemblyName = assemblyNames.ToString();
                var workingFolder = string.Format(@"{0}", this.WorkingFolderName.Get(context));
                var reflectionOrgFileName = string.Format(@"{0}", this.ReflectionOrgFilename.Get(context));
                var path = string.Format("{0}\\{1}", workingFolder, reflectionOrgFileName);
                var outFolder = "\"" + path + "\"";
                var arguments = string.Format("{0} /out:{1}", assemblyName, outFolder);
                try
                {
                    InvokeCommand.ExecuteCommand(context, exeFileName, arguments);
                }
                catch (Exception ex)
                {
                    LogHelper.LogError(context, ex.Message);
                    throw;
                }
            }
        }
    }
}
